// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const rcbRouter = require('tcb-router')
const rp = require('request-promise')

const BASE_URL = 'http://v3.wufazhuce.com:8000/api/'

const findPicsCollection = db.collection('find-pics')
const findEssayCollection = db.collection('find-essay')
const findMusicCollection = db.collection('find-music')

class Bar {
  formatTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    return [year, month, day].map(this.formatNumber).join('-')
  }
  formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }
  async add(collection, data) {
    await collection.add({
      data: data
    }).then(res => {
      console.log('插入成功')
    }).catch(err => {
      console.log('插入失败', err)
    })
  }
  async updata(collection, data, condition) {
    await collection.where(condition).update({
      data
    }).then(res => {
      console.log('更新成功')
    }).catch(err => {
      console.log('更新失败', err)
    })
  }
  isNew(data, time, key) {
    let serverDete = this.formatTime(new Date())
    if (data && serverDete.indexOf(time) > -1) {
      if (this.formatTime(new Date(data.data[0][key])) !== serverDete) {
        return 'update'
      }
    }
    return ''
  }
}

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new rcbRouter({
    event
  })

  app.router('hp', async (ctx) => {
    let bar = new Bar()
    let data, type = ''
    data = await findPicsCollection.where({
      date: event.date
    }).get().then(res => {
      return res.data[0]
    })
    type = await bar.isNew(data, event.date, 'maketime')
    if (!data) {
      data = await rp(BASE_URL + 'hp/bymonth/' + event.date)
        .then((res) => {
          return JSON.parse(res)
        })
      if (data.data) {
        await bar.add(findPicsCollection, {
          data: data.data,
          date: event.date,
          createTime: db.serverDate()
        })
      }
    } else if (type == 'update') {
      data = await rp(BASE_URL + 'hp/bymonth/' + event.date)
        .then((res) => {
          return JSON.parse(res)
        })
      if (data.data) {
        await bar.updata(findPicsCollection, {
          ...data,
          date: event.date,
          updateTime: db.serverDate()
        }, {
          date: event.date
        })
      }
    }
    ctx.body = data
  })

  app.router('essay', async (ctx) => {
    let bar = new Bar()
    let data, type = ''
    data = await findEssayCollection.where({
      date: event.date
    }).get().then(res => {
      return res.data[0]
    })
    type = await bar.isNew(data, event.date, 'hp_makettime')
    if (!data) {
      data = await rp(BASE_URL + 'essay/bymonth/' + event.date)
        .then((res) => {
          return JSON.parse(res)
        })
      if (data.data) {
        await bar.add(findEssayCollection, {
          data: data.data,
          date: event.date,
          createTime: db.serverDate()
        })
      }
    } else if (type == 'update') {
      data = await rp(BASE_URL + 'essay/bymonth/' + event.date)
        .then((res) => {
          return JSON.parse(res)
        })
      if (data.data) {
        await bar.updata(findEssayCollection, {
          ...data,
          date: event.date,
          updateTime: db.serverDate()
        }, {
          date: event.date
        })
      }
    }
    ctx.body = data
  })


  app.router('music', async (ctx) => {
    // let data = await rp(BASE_URL + 'music/bymonth/' + event.date)
    //   .then((res) => {
    //     return JSON.parse(res)
    //   })
    // ctx.body = {
    //   ...data,
    //   date: event.date
    // }
    let bar = new Bar()
    let data, type = ''
    data = await findMusicCollection.where({
      date: event.date
    }).get().then(res => {
      return res.data[0]
    })
    // type = await bar.isNew(data, event.date, 'hp_makettime')
    let serverDete = bar.formatTime(new Date())
    if (data && serverDete.indexOf(event.date) > -1) {
      type = 'update'
    }
    if (!data) {
      data = await rp(BASE_URL + 'music/bymonth/' + event.date)
        .then((res) => {
          return JSON.parse(res)
        })
      if (data.data) {
        await bar.add(findMusicCollection, {
          data: data.data,
          date: event.date,
          createTime: db.serverDate()
        })
      }
    } else if (type == 'update') {
      data = await rp(BASE_URL + 'music/bymonth/' + event.date)
        .then((res) => {
          return JSON.parse(res)
        })
      if (data.data) {
        await bar.updata(findMusicCollection, {
          ...data,
          date: event.date,
          updateTime: db.serverDate()
        }, {
          date: event.date
        })
      }
    }
    ctx.body = data


  })

  return app.serve()
}